//
//  LDYRefreshControl.swift
//  李东阳微博
//
//  Created by 李东阳 on 16/4/22.
//  Copyright © 2016年 李东阳. All rights reserved.
//

import UIKit

 enum LDYRefreshControlType : Int {
        // 正常状态
    case refreshNormal = 0
        // 松手刷新
    case refreshPulling = 1
       // 刷新中
    case refreshing = 2
}


class LDYRefreshControl: UIControl {

    var ldyState:LDYRefreshControlType = .refreshNormal{
    
        didSet{
        
            switch ldyState{
            
            
            case .refreshNormal:
                
              messageLabel.text = "正常状态"
              if oldValue == .refreshing{
                
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.myScrollView?.contentInset.top -= 50
                })
                
                }
                
            case .refreshPulling:
             messageLabel.text = "松手刷新"
               
            case .refreshing:
               messageLabel.text = "刷新中"
                
              UIView.animateWithDuration(0.25, animations: { () -> Void in
                
                self.myScrollView?.contentInset.top += 50
                }, completion: { (_) -> Void in
                        // 告知外界要刷新了
                    self.sendActionsForControlEvents( UIControlEvents.ValueChanged)
                    
              })
            
            }
        
        
        }
    
    }
    
    
    // MARK: - 供外界调用停止刷新
    func endRefreshing(){
        ldyState = .refreshNormal
    }
    
    
    
    var myScrollView: UIScrollView?
    
   override init(frame: CGRect) {
        super.init(frame: frame)
    
    setupUI()
    }

   required init?(coder aDecoder: NSCoder) {
       fatalError("init(coder:) has not been implemented")
   }
    
    
    //MARK: - 设置视图
    private func setupUI(){
    
    self.backgroundColor = RGB(red:55, green: 105, blue: 65)
    
      addSubview(messageLabel)
        
        
    }

    
    override func layoutSubviews() {
        
        super.layoutSubviews()

        //设置frame
        self.frame = CGRect(x: 0, y: -50, width: UIScreeonwidth, height: 50)
        
        messageLabel.frame = CGRect(x: 0, y: 0, width: UIScreeonwidth, height: 50)
        
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        /// 判断控件是否存在 且是否是UIScrollView
        if let myScrollView = newSuperview as? UIScrollView{
//            myScrollView.contentOffset
            
            /**
            * 通过kvo 监听我们父控件的属性改变
            */
            self.myScrollView = myScrollView
        myScrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        }
    }
    
    //监听我们哪个对象的属性发生改变
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        // 获得临界值
        let contentMargin = -(50 + myScrollView!.contentInset.top)
        
         let contenOffsetY  = myScrollView?.contentOffset.y
       
        if myScrollView!.dragging {
        
        if contenOffsetY > contentMargin && ldyState == .refreshPulling {

        ldyState = .refreshNormal
    
        }else if contenOffsetY <= contentMargin && ldyState ==  .refreshNormal {
        ldyState = .refreshPulling
        
        }
    }
    
        else{
        
            if ldyState == .refreshPulling {
            
             ldyState = .refreshing
    }
 }
}
    
    deinit{
        // KVO 需要程序员自己手动移除
        
    self.myScrollView?.removeObserver(self, forKeyPath: "contentOffset")
    
    }
    
    
    private lazy  var messageLabel:UILabel = {
    
    let lab = UILabel(textColor: UIColor.whiteColor(), textFont: 14)
        
       lab.text = "正常状态"
        lab.textAlignment = .Center
        
    return lab
    }()
    
    
}
